package edu.whu.readXML.impl;

import edu.whu.exception.MyException;
import edu.whu.readXML.XMLReader;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.List;

public class Dom4JReader implements XMLReader {

    /**
     *
     * @param filePath
     * @return
     * @throws MyException
     */
    public static Document loadFile(String filePath) throws MyException {
        try {
            //获取文件类型
            String fileType = filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length()).toLowerCase();
            //判断是否为xml类型，如果不是则抛出异常
            if(!fileType.equals("xml")) {
                throw new MyException(MyException.ErrorType.DOCUMENT_TYPE_ERROR,"文件类型错误");
            }
            //判断文件是否为空
            File file = new File(filePath);
            if(file == null) {
                throw new MyException(MyException.ErrorType.FILE_NOT_FOUND,"文件未找到");
            }
            //使用dom4j读取文件
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(file);
            return document;
        } catch (DocumentException e) {
            throw new MyException(MyException.ErrorType.DOCUMENT_READ_ERROR,"文件读取失败");
        }
    }

    /**
     * 获取根元素，并判断是否为beans
     * @param document
     * @return
     */
    public static Element getRoot(Document document) throws MyException{
        Element rootElement = document.getRootElement();
        if(!rootElement.getName().equals("beans")) {
            throw new MyException(MyException.ErrorType.ROOT_TYPE_ERROR,"根元素标签错误");
        }
        return rootElement;
    }

    //获取某一名字的所有子节点
    public static List<Element> getChild(Element father, String name) {
        return father.elements(name);
    }

    //获取所有的bean标签节点
    public static List<Element> getBean(Element root) {
        return getChild(root,"bean");
    }

    //获取bean标签里的property标签节点
    public static List<Element> getProperty(Element bean) {
        return getChild(bean, "property");
    }
}
